from functools import wraps
from typing import Optional

import pyautogui
from playwright.sync_api import BrowserContext, Page
import pygetwindow as gw


def activate_before(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        self.activate()
        return func(self, *args, **kwargs)

    return wrapper


class AutoBrowser:
    def __init__(self, browser: BrowserContext, name: str):
        self.browser = browser
        self.name = name

        windows = gw.getWindowsWithTitle(self.name)
        if not windows:
            assert "Failed to find the identification page"
        self.window = windows[0]

    def activate(self):
        """
        每隔一秒检查一次浏览器是否处于激活张你太
        :return: bool
        """
        active_window = gw.getActiveWindow()
        if not active_window or active_window.title != self.window.title:
            self.window.activate()

    @classmethod
    def move_cursor(cls, x: int, y: int, duration: float = 0.1):
        pyautogui.moveTo(x, y, duration=duration)

    @activate_before
    def new_page(self, url: str = None) -> Page:
        """
        打开网页
        :param url: 网页地址
        :return: 页面对象
        """
        page = self.browser.new_page()
        if url:
            page.goto(url)
        return page

    def get_active_page(self) -> Optional[Page]:
        """
        获取当前停留的页面
        :return: 页面对象
        """
        self.activate()

        for page in self.browser.pages:
            if page.evaluate("document.hasFocus()"):
                return page

    @activate_before
    def maximize(self) -> bool:
        """
        最大化浏览器窗口
        :return:
        """
        # 如果是已经是最小化状态，应恢复窗口
        if self.window.isMinimized:
            self.window.restore()

        # 最大化窗口
        self.window.maximize()

        return True

    @activate_before
    def click_element(self):
        """
        点击元素
        :return:
        """
        # 在点击点击元素之前，应让鼠标随机移动
        self.move_cursor(10, 10)

        a=1

